<template>
  <div class="content-detail">
    <div>
      <el-card class="card-box">
        <div class="card-box--headerwrap">
          <el-page-header
            icon="el-icon-arrow-left"
            content="权限分配"
            @back="handleBack"
          ></el-page-header>
          <div class="content__btn">
            <el-button @click="handleBack">取 消</el-button>
            <el-button type="primary" @click="handleSubmit">保 存</el-button>
          </div>
        </div>
      </el-card>

      <el-card class="card-box">
        <div class="card-box--headerwrap">
          <div class="card-box-header">
            <el-page-header
              icon="el-icon-user"
              title="角色名称"
              :content="roleName"
            ></el-page-header>
          </div>
        </div>
      </el-card>
    </div>

    <div class="detail">
      <el-card class="card-box card-item">
        <div class="sub">菜单权限配置</div>
        <div class="menu-content">
          <p class="tips">
            (注意：点击保存后，该角色将<span>拥有</span>已选中菜单权限)
          </p>
          <el-tree
            :data="menuList"
            show-checkbox
            default-expand-all
            node-key="id"
            ref="treeRef"
            highlight-current
            :props="defaultProps"
          >
          </el-tree>
        </div>
      </el-card>

      <el-card class="card-box card-item-right">
        <div class="sub">按钮权限配置</div>
        <div class="menu-content">
          <p class="tips">
            (注意：点击保存后，该角色<i>不拥有</i>已勾选的按钮权限)
          </p>
          <div v-for="item in resourceList" :key="item.id">
            <el-checkbox
              text-color="#000"
              fill="#000"
              v-model="item.isActive"
              :indeterminate="item.isIndeterminate"
              @change="handleAllCheck(item)"
              >{{ item.resourceGroupName }}</el-checkbox
            >
            <br />
            <el-checkbox-group
              text-color="#000"
              fill="#000"
              v-model="item.isActiveChild"
              :key="item.id"
              @change="handleCheckedCitiesChange(item)"
            >
              <el-checkbox
                text-color="#000"
                fill="#000"
                v-for="i in item.resourceList"
                :key="i.id"
                :label="i.id"
                >{{ i.resourceName }}</el-checkbox
              >
            </el-checkbox-group>
            <el-divider></el-divider>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script lang="ts">
import { useRoute, useRouter } from "vue-router";
import { defineComponent, reactive, toRefs, ref } from "vue";
import NotifMessage from "/@/utils/message/notification";
import { storageLocal } from "/@/utils/storage";
import {
  resourceGroupList,
  getRoleResourceAuth,
  saveRoleResourceAuth,
  menuGroupList,
  getRoleMenuAuth,
  saveRoleMenuAuth
} from "/@/api/projects";
import { cloneDeep } from "lodash-es";
export default defineComponent({
  name: "resourceSet",
  setup() {
    const router = useRouter();
    const route = useRoute();
    let treeRef = ref<HTMLElement | null>(null) as any;
    let roleId = ref(route.query.roleId);
    let roleName = ref(route.query.roleName);
    let state = reactive({
      resourceList: [],
      resourceAuth: [],
      menuList: [],
      menuAuth: []
    });

    const defaultProps = {
      children: "children",
      label: "menuName"
    };

    const fnFilterData = list => {
      return list.map(item => {
        return { id: item };
      });
    };

    const handleSubmit = async () => {
      updateRoleMenuAuth();
    };

    //更新角色资源权限
    const updateRoleResourceAuth = async () => {
      let newGroupList = [];
      const copyResourceList = cloneDeep(state.resourceList);
      copyResourceList.map(item => {
        if (item.isActiveChild.length) {
          newGroupList.push({
            id: item.id,
            resourceGroupKey: item.resourceGroupKey,
            resourceList: fnFilterData(item.isActiveChild)
          });
        }
      });
      const params = {
        roleId: roleId.value,
        includeType: "0",
        resGroupList: newGroupList,
        projectManageId: storageLocal.getItem("projectInfo")?.id,
        projectName: storageLocal.getItem("projectInfo")?.name
      };

      try {
        const { code, message } = await saveRoleResourceAuth(params);
        if (code === 200) {
          NotifMessage.success(message);
          handleBack();
        } else {
          message && NotifMessage.error(message);
        }
      } catch (err) {
        console.log(err);
      }
    };

    //更新角色菜单权限
    const updateRoleMenuAuth = async () => {
      const postMenu = getCheckedNodes();
      if (!postMenu.length) {
        NotifMessage.error("请至少选择一个菜单");
        return;
      }
      const params = {
        role: { id: roleId.value },
        menus: postMenu
      };
      try {
        const { code, message } = await saveRoleMenuAuth(params);
        if (code === 200) {
          updateRoleResourceAuth();
        } else {
          message && NotifMessage.error(message);
        }
      } catch (err) {
        console.log(err);
      }
    };

    // 获取角色资源列表
    async function getTableData(obj: object = {}) {
      try {
        const { code, data } = await resourceGroupList(obj);
        if (code === 200) {
          data.forEach(item => {
            item.isActive = false;
            item.isActiveChild = [];
            item.isIndeterminate = false;
          });
          state.resourceList = data;
        }
      } catch (err) {
        console.log(err);
      }
    }

    // 获取角色拥有的资源权限
    async function getInitResourceAuth(obj: object = {}) {
      try {
        const { code, data } = await getRoleResourceAuth(obj);
        if (code === 200) {
          state.resourceAuth = data.resGroupList;
        }
      } catch (err) {
        console.log(err);
      }
    }

    // 获取角色菜单列表
    async function getMenuGroupList(obj: object = {}) {
      try {
        const { code, data } = await menuGroupList(obj);
        if (code === 200) {
          data.forEach(item => {
            item.isActive = false;
            item.isActiveChild = [];
            item.isIndeterminate = false;
          });
          data.forEach(item => {
            if (item?.children?.length) {
              // item.children = item.children.slice(0, 2);
              item.children = item.children.filter(item => item.isDisplay === 'Y')
            }
          });
          state.menuList = data;
        }
      } catch (err) {
        console.log(err);
      }
    }

    // 获取角色拥有的菜单权限
    async function getInitRoleMenuAuth(obj: object = {}) {
      try {
        const { code, data } = await getRoleMenuAuth(obj);
        if (code === 200) {
          state.menuAuth = data;
          let newArr = [];
          data.forEach(item => {
            checked(item, state.menuList, newArr);
            treeRef.value.setCurrentKey(item); //自动展开到选中的节点那一层
          });
          treeRef.value.setCheckedKeys(newArr);
        }
      } catch (err) {
        console.log(err);
      }
    }

    const initTable = async () => {
      await getMenuGroupList({ menuPathLike: "/projectsA" });
      await getInitRoleMenuAuth({ roleId: roleId.value });
      await getTableData({ isProjectResource: "1", projectResourceType: "A" });
      await getInitResourceAuth({ roleId: roleId.value });
      state?.resourceAuth?.length &&
        state.resourceAuth.forEach(item => {
          state.resourceList.forEach(i => {
            if (i.id === item.id) {
              const newList =
                item.resourceList.length &&
                item.resourceList.map(x => {
                  return x.id;
                });
              i.isActiveChild = newList;
              if (i.resourceList.length === newList.length) {
                i.isActive = true;
              } else {
                i.isIndeterminate = true;
              }
            }
          });
        });
    };

    //菜单回填
    // const menuDataFill = async () =>{
    //   state?.menuAuth?.length && state.menuAuth.forEach(item => {
    //     state.menuList.forEach(i => {
    //       if (i.id === item) {
    //         const newList = [...state.menuAuth];
    //         i.isActiveChild = newList;
    //         if (i.children.length === newList.length) {
    //           i.isActive = true;
    //         } else {
    //           i.isIndeterminate = true;
    //         }
    //       }
    //     });
    //   });
    // }

    initTable();

    const checked = (id, data, newArr) => {
      data.forEach(item => {
        if (item.id == id) {
          if (item.children.length == 0) {
            newArr.push(item.id);
          }
        } else {
          if (item.children.length != 0) {
            checked(id, item.children, newArr);
          }
        }
      });
    };

    const getCheckedNodes = () => {
      const newData = treeRef.value
        .getCheckedKeys()
        .concat(treeRef.value.getHalfCheckedKeys());
      return newData;
    };

    const handleCheckedCitiesChange = item => {
      if (item.isActiveChild.length === item.resourceList.length) {
        item.isActive = true;
      } else {
        item.isActive = false;
      }

      if (
        item.isActiveChild.length > 0 &&
        item.isActiveChild.length !== item.resourceList.length
      ) {
        item.isIndeterminate = true;
      } else {
        item.isIndeterminate = false;
      }
    };

    const handleAllCheck = item => {
      if (item.isActive) {
        item.isActiveChild = item.resourceList.map(x => {
          return x.id;
        });
      } else {
        item.isActiveChild = [];
      }
      if (
        item.isActiveChild.length > 0 &&
        item.isActiveChild.length !== item.resourceList.length
      ) {
        item.isIndeterminate = true;
      } else {
        item.isIndeterminate = false;
      }
    };

    // 返回按钮事件
    const handleBack = () => {
      router.push("/projectsA/proManage/permission");
    };

    return {
      ...toRefs(state),
      handleCheckedCitiesChange,
      handleAllCheck,
      handleSubmit,
      updateRoleMenuAuth,
      updateRoleResourceAuth,
      defaultProps,
      treeRef,
      handleBack,
      roleName
    };
  }
});
</script>

<style lang="scss" scoped>
.content-detail {
  width: 100%;
  height: 100%;
  font-weight: 400;
  background: #ffffff;
  font-family: PingFangSC-Medium, PingFang SC;
  .detail {
    display: flex;
    margin-top: 8px;
    height: calc(100% - 112px);
    .card-item {
      margin-right: 4px;
      margin-bottom: 0;
      &-right {
        flex: 1;
        :deep .el-checkbox__input.is-indeterminate .el-checkbox__inner {
          background: #e45d5d;
          border-color: #e45d5d;
        }
        :deep .el-checkbox__input.is-indeterminate .el-checkbox__inner::before {
          content: "";
          position: absolute;
          display: block;
          background-color: #fff;
          height: 2px;
          transform: scale(0.5);
          left: 0;
          right: 0;
          top: 5px;
          width: auto;
        }
        :deep .el-checkbox__input.is-checked .el-checkbox__inner {
          background: #e45d5d;
          border-color: #e45d5d;
        }
        :deep .el-checkbox__input.is-checked .el-checkbox__inner::after {
          transform: rotate(-45deg) scaleY(1);
        }
        :deep .el-checkbox__input.is-checked .el-checkbox__inner::before {
          transform: rotate(45deg) scaleY(1);
        }
        :deep .el-checkbox__inner::after {
          position: absolute;
          content: " ";
          background-color: #eee;
          left: 5px;
          top: 0;
          width: 1px;
          height: 12px;
          transform: rotate(-45deg) scaleY(0);
          box-sizing: border-box;
          border: none;
        }
        :deep .el-checkbox__inner::before {
          position: absolute;
          content: " ";
          background-color: #eee;
          left: 5px;
          top: 0;
          width: 1px;
          height: 12px;
          transform: rotate(45deg) scaleY(0);
          box-sizing: border-box;
          border: none;
        }
      }
    }
    .sub {
      font-size: 14px;
      font-weight: 500;
      color: #494c53;
      padding: 14px 0 14px 16px;
      border-bottom: 1px solid #c2cade;
    }
    .menu-content {
      min-width: 352px;
      padding: 12px 16px 0 16px;
      .tips {
        font-size: 12px;
        color: #8895b7;
        margin-bottom: 12px;
        span {
          color: #5298ff;
        }
        i {
          color: #e45d5d;
          font-style: normal;
        }
      }
      :deep .el-checkbox__inner {
        border-radius: 1px;
        border-radius: 0;
      }
    }
  }
  .content__btn {
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }

  .tree-classtree :deep {
    .el-tree-node__content {
      color: #626aef;
    }
  }
  // .content__body {
  //   width: 100%;
  //   flex: 1;
  //   padding: 8px 16px;
  //   overflow-y: auto;
  //   &--title {
  //     font-size: 14px;
  //     color: #606266;
  //     line-height: 32px;
  //     margin-bottom: 10px;
  //   }
  // }
}

// .btn-last {
//   :deep .el-radio-button__original-radio:checked + .el-radio-button__inner {
//     background: red;
//     border-color: red;
//     box-shadow: -1px 0 0 red;
//   }
// }
</style>
